from flask import g
from flask_restful import Resource
from flask_restful.reqparse import RequestParser

from comment.utils.gen_trans_id import gen_trans_id
from comment.modules import db
from comment.modules.user import User
from comment.utils.decorators import login_required
from comment.modules.account import Account
from comment.modules.deal_record import DealRecord
from financial.resources.account.serializer import AccountInfoSerializer
from financial.resources.transaction.const import DealType


class AccountInfo(Resource):
    # 使用了登录拦截的装饰器
    method_decorators = [login_required]

    def get(self):
        """查询当前用户的资金账户"""
        user_id = g.user_id
        acc = Account.query.filter(Account.userId == user_id).first()

        if acc:
            return AccountInfoSerializer(acc).to_dict()
        else:
            return {'message': '资金账户不存在'}, 400


class AccountExtract(Resource):
    # 使用了登录拦截的装饰器
    method_decorators = [login_required]

    def post(self):
        """提现的接口"""
        rp = RequestParser()
        rp.add_argument('amount', required=True)  # 金额
        rp.add_argument('card_id', required=True)  # 卡号
        rp.add_argument('payPwd', required=True)  # 支付密码

        args = rp.parse_args()
        amount = float(args.amount)
        card_id = args.card_id
        pay_pwd = args.payPwd

        user_id = g.user_id
        # 查询当前登录的用户
        user = User.query.filter(User.id == user_id).first()

        if not user.check_pay_password(pay_pwd):
            return {'code': 20001, 'message': '支付密码错误'}

        # 查询用户资金账户
        acc = Account.query.filter(Account.userId == user_id).first()

        if acc:
            if acc.balance < amount: # 当前资金账户余额超出 提现金额
                return {'message': '超出了可提取的金额'}, 400
            else:
                # 交易之前的可用余额
                before_balance = acc.balance
                # 修改新的余额
                acc.balance = float(acc.balance) - amount
                # 修改新的总金额
                acc.total = float(acc.total) - amount
                # 生成流水号
                deal_num = gen_trans_id(DealType.extract.name)

                """ 提现： 调用银行的接口实现真正的提现"""

                # 新增一条交易记录对象
                deal_log = DealRecord(aUserId=user_id, aReceiveOrPay=1, aTransferSerialNo=deal_num,
                                      aTransferStatus=1, aBeforeTradingMoney=before_balance, aAmount=amount,
                                      aAfterTradingMoney=acc.balance, aDescreption='提现',
                                      aType=DealType.extract.value)
                db.session.add(deal_log)
                db.session.commit()
                return {'msg': 'success'}


# 充值
class AccountRecharge(Resource):
    """资金账户的充值"""

    def post(self):
        rp = RequestParser()
        rp.add_argument('amount', required=True)  # 金额
        rp.add_argument('selectedIndex', required=True)  # 选择的充值银行卡

        args = rp.parse_args()
        amount = float(args.amount)
        selected_bank_id = args.selectedIndex

        user_id = g.user_id
        # # 查询当前登录的用户
        # user = User.query.filter(User.id == user_id).first()

        # 查询用户资金账户
        acc = Account.query.filter(Account.userId == user_id).first()

        if acc:
            # 交易之前的可用余额
            before_balance = acc.balance
            # 修改新的余额
            acc.balance = float(acc.balance) + amount
            # 修改新的总金额
            acc.total = float(acc.total) + amount
            # 生成流水号
            deal_num = gen_trans_id(DealType.recharge.name)

            """ 充值： 调用银行的接口实现真正的充值"""

            # 新增一条交易记录对象
            deal_log = DealRecord(aUserId=user_id, aReceiveOrPay=0, aTransferSerialNo=deal_num,
                                  aTransferStatus=1, aBeforeTradingMoney=before_balance, aAmount=amount,
                                  aAfterTradingMoney=acc.balance, aDescreption='充值',
                                  aType=DealType.recharge.value)
            db.session.add(deal_log)
            db.session.commit()
            return {'msg': 'success'}
